package view;

import app.App;
import model.Product;
import model.StockIn;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DialogStockIn extends JDialog {

    private final static int INIT_W = 320;  //窗体初始宽度
    private final static int INIT_H = 420;  //窗体初始高度

    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField tf_stockInId;
    private JTextField tf_vendor;
    private JCheckBox checkbox_isNew;
    private JComboBox<String> comboBox_id;
    private JTextField tf_productId;
    private JTextField tf_productName;
    private JFormattedTextField tf_purchasePrice;
    private JFormattedTextField tf_count;
    private JFormattedTextField tf_sellingPrice;
    private JTextField tf_category;

    WarehousePane warehousePane;
    List<Product> productList = new ArrayList<>();
    boolean isComboBoxUpdating;

    private void createUIComponents() {
        //输入字符限制
        NumberFormat nf = NumberFormat.getInstance();
        tf_sellingPrice = new JFormattedTextField(nf);
        tf_purchasePrice = new JFormattedTextField(nf);

        NumberFormat nf_int = NumberFormat.getIntegerInstance();
        nf_int.setGroupingUsed(false);
        tf_count = new JFormattedTextField(nf_int);
    }

    public DialogStockIn(WarehousePane warehousePane) {
        this.warehousePane = warehousePane;
        //自动输入新的商品号
        tf_productId.setText(String.valueOf(Product.getNewProductId()));

        setTitle("填写入库单");
        setPreferredSize(new Dimension(INIT_W, INIT_H));
        pack();
        setResizable(false);
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        //居中
        Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        setBounds(p.x - getWidth() / 2, p.y - getHeight() / 2, getWidth(), getHeight());

        //自动设置一个入库号
        tf_stockInId.setText(String.valueOf(StockIn.getNewStockInId()));

        buttonOK.addActionListener(e -> onOK());

        buttonCancel.addActionListener(e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(
                e -> onCancel(),
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        checkbox_isNew.addItemListener(e -> {
            if (checkbox_isNew.isSelected()) {//是新商品时
                //禁用下拉框、启用其他，除了数量
                comboBox_id.setEnabled(false);
                tf_productName.setEditable(true);tf_category.setEditable(true);
                tf_purchasePrice.setEditable(true);tf_sellingPrice.setEditable(true);
                //自动输入商品号
                tf_productId.setText(String.valueOf(Product.getNewProductId()));
                //清空文本
                tf_productName.setText(null);tf_category.setText(null);
                tf_purchasePrice.setText(null);tf_sellingPrice.setText(null);
            }
            else {//是旧商品时
                isComboBoxUpdating = true;
                //启用下拉框、禁用其他，除了数量
                comboBox_id.setEnabled(true);
                tf_productName.setEditable(false);tf_category.setEditable(false);
                tf_purchasePrice.setEditable(false);tf_sellingPrice.setEditable(false);
                //如果当前商品列表有改变，更新下拉框选项
                if (!productList.equals(App.currentProductList)){
                    productList = App.currentProductList;

                    comboBox_id.removeAllItems();
                    for (Product product : App.currentProductList) {
                        comboBox_id.addItem(product.getProductId() + " \"" + product.getProductName() + "\"");
                    }
                }
                //自动输入第一个商品的信息
                Product firstProduct = productList.get(0);
                tf_productId.setText(String.valueOf(firstProduct.getProductId()));
                tf_productName.setText(firstProduct.getProductName());
                tf_category.setText(firstProduct.getCategory());
                tf_purchasePrice.setText(String.valueOf(firstProduct.getPurchasePrice()));
                tf_sellingPrice.setText(String.valueOf(firstProduct.getSellingPrice()));
                isComboBoxUpdating = false;
            }
        });

        //当选择旧商品时，自动输入商品的信息
        comboBox_id.addItemListener(e -> {
            if (!isComboBoxUpdating) {
                Product selectedProduct = productList.get(comboBox_id.getSelectedIndex());
                tf_productId.setText(String.valueOf(selectedProduct.getProductId()));
                tf_productName.setText(selectedProduct.getProductName());
                tf_category.setText(selectedProduct.getCategory());
                tf_purchasePrice.setText(String.valueOf(selectedProduct.getPurchasePrice()));
                tf_sellingPrice.setText(String.valueOf(selectedProduct.getSellingPrice()));
            }
        });
    }

    private void onOK() {
        if (!tf_stockInId.getText().isBlank()) {
            if(!tf_vendor.getText().isBlank()) {
                if (!(tf_productId.getText().isBlank() || tf_productName.getText().isBlank() ||
                        tf_category.getText().isBlank() || tf_purchasePrice.getText().isBlank() ||
                        tf_sellingPrice.getText().isBlank() || tf_count.getText().isBlank())) {
                    //确认
                    if (JOptionPane.showConfirmDialog(this, "是否提交当前入库单？", "确认入库", JOptionPane.OK_CANCEL_OPTION) == 0) {
                        //记录入库订单并入库商品（事务）
                        if (StockIn.stockIn(getStockIn())) {
                            JOptionPane.showMessageDialog(this, "入库成功！", null, JOptionPane.INFORMATION_MESSAGE);
                            warehousePane.notifyProductDataChanged();
                            warehousePane.notifyInHistoryDataChanged();
                            dispose();
                        }
                        else {
                            JOptionPane.showMessageDialog(this, "入库失败！", null, JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
                else {
                    JOptionPane.showMessageDialog(this, "商品信息不完整", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
            else {
                JOptionPane.showMessageDialog(this, "请填写供应商", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
        else {
            JOptionPane.showMessageDialog(this, "请填写入库号", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }

    //从输入框获取入库单
    StockIn getStockIn() {
        try {
            int stockInId = Integer.parseInt(tf_stockInId.getText());
            int productId = Integer.parseInt(tf_productId.getText());
            String productName = tf_productName.getText();
            float purchasePrice = Float.parseFloat(tf_purchasePrice.getText());
            int count = Integer.parseInt(tf_count.getText());
            String vendor = tf_vendor.getText();

            String category = tf_category.getText();
            float sellingPrice = Float.parseFloat(tf_sellingPrice.getText());

            return new StockIn(
                    stockInId,
                    productId,
                    productName,
                    purchasePrice,
                    count,
                    vendor,
                    new Timestamp(new Date().getTime()),
                    new Product(
                            productId,
                            productName,
                            category,
                            purchasePrice,
                            sellingPrice,
                            count
                    )
            );
        }catch (NumberFormatException exception) {
            JOptionPane.showMessageDialog(this, "请填写入库号", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return null;
    }
}
